package com.tjetc.proxy;

import com.tjetc.vo.Result;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class ClientProxy {
    public static <T> T getProxyInstance(Class<T> clz){
        return (T)Proxy.newProxyInstance(clz.getClassLoader(), new Class[]{clz}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Socket socket=new Socket("10.64.167.73",8888);
//                Socket socket=new Socket("localhost",8888);
                ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
                //写出接口名称
                out.writeUTF(clz.getSimpleName());
                //写出方法名
                out.writeUTF(method.getName());
                //写入方法参数类型
                out.writeObject(method.getParameterTypes());
                //写入方法参数
                out.writeObject(args);
                //获取返回值
//                Result result=(Result) in.readObject();
                Object result=in.readObject();
                out.close();
                in.close();
                socket.close();
                return result;
            }
        });
    }
}
